import { useEffect, useState } from "react";
import {
  Button,
  StyleSheet,
  Text,
  View,
  TextInput,
  ActivityIndicator,
} from "react-native";
import Loading from "./components/Loading";

export default function App() {
  const [courses, setCourses] = useState([]);
  const [keyword, setKeyword] = useState("");
  const [loading, setLoading] = useState(false);
  const fetchData = async (keyword: string) => {
    setLoading(true);
    try {
      await new Promise((resolve) => setTimeout(resolve, 3000));
      const res = await fetch(`http://192.168.3.4:3005/search?q=${keyword}`);
      const { data } = await res.json();
      console.log(data);
      setCourses(data.courses);
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData(keyword);
  }, [keyword]);

  if (loading) {
    return <Loading />;
  }

  return (
    <View style={styles.container}>
      <Text>您搜索的关键词是：{keyword}</Text>

      <TextInput
        style={styles.input}
        placeholder="请填写要所搜索的课程!"
        onChangeText={(text) => setKeyword(text)}
        defaultValue={keyword}
      />

      {courses.length > 0 ? (
        courses.map((course: any) => <Text key={course.id}>{course.name}</Text>)
      ) : (
        <Text>没有找到课程</Text>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  input: {
    height: 40,
    width: 300,
    margin: 12,
    padding: 10,
    borderWidth: 1,
    borderColor: "#ccc",
    borderRadius: 5,
  },
});
